package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class RegisterActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "RegisterActivity";
    private EditText Et_UserName,Et_AcNum,Et_PassWord,Et_rePassWord,Et_TelPhone,Et_Problem,Et_Answer;
    private Button Btn_Yes,Btn_Back;
    private String AccountNumber;
    private String TelPhone;
    private int close;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        Et_UserName = findViewById(R.id.Et_UserName);
        Et_AcNum = findViewById(R.id.Et_AcNum);
        Et_PassWord = findViewById(R.id.Et_PassWord);
        Et_rePassWord = findViewById(R.id.Et_rePassWord);
        Et_TelPhone = findViewById(R.id.Et_TelPhone);
        Et_Problem = findViewById(R.id.Et_Problem);
        Et_Answer = findViewById(R.id.Et_Answer);

        Btn_Yes = findViewById(R.id.Btn_Yes);
        Btn_Back = findViewById(R.id.Btn_Back);

        Btn_Yes.setOnClickListener(this);
        Btn_Back.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
            switch (v.getId()){
                case R.id.Btn_Yes:
                    user();

                    break;

                case R.id.Btn_Back:
                    Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
                    startActivity(intent);
                    break;

            }

    }

    private void user() {
        new Thread(new Runnable() {
            private static final String TAG = "MainActivity";
            @Override
            public void run() {
                //1 client对象
                OkHttpClient client = new OkHttpClient();
                //2 Request对象
                FormBody body = new FormBody.Builder()

                        .build();
                Request request = new Request.Builder()

                        .url("http://10.2.64.68:8080/juyuan/users/list?accountNumber="+Et_AcNum.getText().toString() )
                        .post(body)
                        .build();
                //3 call对象
                final Call call = client.newCall(request);
                //4 执行call对象得到数据
                try {
                    Response response = call.execute();
                    final String data = response.body().string();
                    Log.e(TAG, "run: "+ data.equals("null"));
                    if (data.equals("null")){
                        //判断用户是否存在 存在=1；不存在=0；
                            close = 0;

                            //调用注册方法
                            register();

                            //脱离线程
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(RegisterActivity.this, "注册成功！", Toast.LENGTH_SHORT).show();
                                Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
                                startActivity(intent);
                            }
                        });


                    }else if(!data.equals("null")){
                        close = 1;
                        Gson gson = new Gson();
                        final LoginGson gu = gson.fromJson(data, LoginGson.class);

                        AccountNumber = gu.getAccountNumber();
                        TelPhone = gu.getTelphone();
                    }



                    //脱离线程
                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            if (close == 1){
                                Toast.makeText(RegisterActivity.this, "该账号已存在！", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }).start();

    }

    private void register() {
        final String J_name= Et_UserName.getText().toString();
        final String J_AcNum = Et_AcNum.getText().toString();
        final String J_password = Et_PassWord.getText().toString();
        final String J_rePassWord = Et_rePassWord.getText().toString();
        final String J_TelPhone = Et_TelPhone.getText().toString();
        final String J_Problem = Et_Problem.getText().toString();
        final String J_Answer = Et_Answer.getText().toString();


        if(!J_password.equals(J_rePassWord)){
            Toast.makeText(this, "两次输入的密码不正确！", Toast.LENGTH_SHORT).show();
            return;
        }
        if (J_name.equals("")||J_AcNum.equals("")||J_password.equals("")||J_TelPhone.equals("")||
                J_Problem.equals("")||J_Answer.equals("")){
            Toast.makeText(this, "输入的数据不能为空！", Toast.LENGTH_SHORT).show();
            return;
        }
        new Thread(new Runnable() {
            private static final String TAG = "MainActivity";

            @Override
            public void run() {
                //1 client对象
                OkHttpClient client = new OkHttpClient();
                //2 Request对象(参数1：数据类型 参数2传递的json串）
                JSONObject object = new JSONObject();

                try {
                    object.put("accountNumber", J_AcNum);
                    object.put("answer", J_Answer);
                    object.put("passWord", J_password);
                    object.put("problem", J_Problem);
                    object.put("telphone", J_TelPhone);
                    object.put("userName", J_name);

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                String json = object.toString();
                RequestBody body = FormBody.create(MediaType.parse("application/json:charset=utf-8"), json);
                //构建一个Request，将FormBody作为Post方法的参数传入，
                if (J_password.equals(J_rePassWord)) {
                    Request request = new Request.Builder()
                            .url("http://10.2.64.68:8080/juyuan/users/addUser?accountNumber=" +
                                    ""+J_AcNum+"&answer="+J_Answer+"&passWord="+J_password+"&problem="+J_Problem+"" +
                                    "&telphone="+J_TelPhone+"&userName="+J_name+"")
                            .post(body)
                            .build();
                    //3 call对象
                    Call call = client.newCall(request);
                    //调度Call对象
                    call.enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            Log.e(TAG, "onFailure: " + e);
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            Log.e(TAG, "PostJson: " + response.body().string());

                        }
                    });
                }

            }

        }).start();

    }

}